import re
import ast
from semantic_nav.log_utils import get_logger
logger = get_logger()


def extract_json_code_blocks(input_string):
    """
    Extracts code blocks from markdown text.

    Args:
      input_string: The text to extract from.

    Returns:
      A list of code blocks.
    """
    code_blocks = []
    # *? -> regular expression ending in ? is non-greedy match (match the shortest substring that satisfies the pattern)
    for match in re.findall(r"```json(.*?)```", input_string, re.DOTALL):
        # str.strip([chars]) -> Remove leading and trailing characters
        code_blocks.append(match.strip())  # Remove leading and trailing whitespace
    return code_blocks


def extract_list(input_string):
    try:
        # extract List sections using regular expressions
        match = re.search(r"\[.*\]", input_string, re.DOTALL) # re.DOTALL means `.` match all characters including newlines
        if not match:
            raise ValueError("No valid list found in input string.")
        list_str = match.group()
        # convert string to list using ast.literal_eval() safely
        parsed_list = ast.literal_eval(list_str)
        return parsed_list
    except (ValueError, SyntaxError) as e:
        logger.error(f"Parsing error: {e}")
        return None
